package com.furnitur.modules.admin.service.merchant.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.furnitur.core.entity.product.Furniture;
import com.furnitur.core.entity.user.Merchant;
import com.furnitur.core.entity.user.User;
import com.furnitur.core.mapper.cart.CartMapper;
import com.furnitur.core.mapper.product.FurnitureMapper;
import com.furnitur.core.mapper.review.ReviewMapper;
import com.furnitur.core.mapper.user.MerchantMapper;
import com.furnitur.core.mapper.user.UserMapper;
import com.furnitur.core.mapper.order.OrderItemMapper;
import com.furnitur.core.mapper.order.OrderMapper;
import com.furnitur.core.service.UserService;
import com.furnitur.modules.admin.dto.auth.PasswordUpdateDTO;
import com.furnitur.modules.admin.dto.merchant.MerchantUpdateDTO;
import com.furnitur.modules.admin.dto.merchant.MerchantVO;
import com.furnitur.modules.admin.service.merchant.MerchantService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class MerchantServiceImpl implements MerchantService {

    private static final Logger log = LoggerFactory.getLogger(MerchantServiceImpl.class);

    @Autowired
    private MerchantMapper merchantMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Autowired
    private FurnitureMapper furnitureMapper;
    
    @Autowired
    private CartMapper cartMapper;
    
    @Autowired
    private ReviewMapper reviewMapper;
    
    @Autowired
    private OrderItemMapper orderItemMapper;
    
    @Autowired
    private OrderMapper orderMapper;

    @Override
    public Merchant getCurrentMerchantInfo() {
        User currentUser = userService.getCurrentUser();
        log.info("Current user: {}", currentUser);
        
        if (currentUser == null || !currentUser.getRoleId().equals(2L)) {
            throw new RuntimeException("非商家用户");
        }
        
        Merchant merchant = getMerchantByUserId(currentUser.getId());
        log.info("Found merchant: {}", merchant);
        
        if (merchant == null) {
            throw new RuntimeException("商家信息不存在");
        }
        
        return merchant;
    }

    @Override
    @Transactional
    public void updateMerchantInfo(Merchant merchant) {
        User currentUser = userService.getCurrentUser();
        log.info("Updating merchant info for user: {}", currentUser);
        
        if (currentUser == null || !currentUser.getRoleId().equals(2L)) {
            log.warn("Non-merchant user attempting to update merchant info: {}", currentUser);
            throw new RuntimeException("非商家用户");
        }
        
        Merchant existingMerchant = getMerchantByUserId(currentUser.getId());
        if (existingMerchant == null) {
            log.error("Merchant not found for user: {}", currentUser.getId());
            throw new RuntimeException("商家信息不存在");
        }
        
        log.info("Found existing merchant: {}", existingMerchant);
        
        // 只允许修改部分字段
        existingMerchant.setShopName(merchant.getShopName());
        existingMerchant.setShopLogo(merchant.getShopLogo());
        existingMerchant.setDescription(merchant.getDescription());
        existingMerchant.setAddress(merchant.getAddress());
        existingMerchant.setBusinessLicense(merchant.getBusinessLicense());
        
        log.info("Updating merchant with: {}", existingMerchant);
        
        try {
            merchantMapper.updateById(existingMerchant);
        } catch (Exception e) {
            log.error("Error updating merchant info", e);
            throw new RuntimeException("更新商家信息失败: " + e.getMessage());
        }
    }

    @Override
    public Merchant getMerchantById(Long id) {
        return merchantMapper.selectById(id);
    }

    @Override
    public Merchant getMerchantByUserId(Long userId) {
        return merchantMapper.selectOne(
            new QueryWrapper<Merchant>()
                .eq("user_id", userId)
        );
    }

    @Override
    public void updatePassword(PasswordUpdateDTO dto) {
        User currentUser = userService.getCurrentUser();
        if (currentUser == null || !currentUser.getRoleId().equals(2L)) {
            throw new RuntimeException("非商家用户");
        }

        if (!passwordEncoder.matches(dto.getOldPassword(), currentUser.getPassword())) {
            throw new RuntimeException("原密码错误");
        }

        if (!dto.getNewPassword().equals(dto.getConfirmPassword())) {
            throw new RuntimeException("新密码与确认密码不一致");
        }

        currentUser.setPassword(passwordEncoder.encode(dto.getNewPassword()));
        userMapper.updateById(currentUser);
    }

    @Override
    public MerchantVO getMerchantProfile() {
        User currentUser = userService.getCurrentUser();
        if (currentUser == null || !currentUser.getRoleId().equals(2L)) {
            throw new RuntimeException("非商家用户");
        }

        Merchant merchant = getMerchantByUserId(currentUser.getId());
        if (merchant == null) {
            throw new RuntimeException("商家信息不存在");
        }

        MerchantVO vo = new MerchantVO();
        BeanUtils.copyProperties(merchant, vo);
        vo.setUsername(currentUser.getUsername());
        vo.setPhone(currentUser.getPhone());
        
        return vo;
    }

    @Override
    @Transactional
    public void updateMerchantProfile(MerchantUpdateDTO dto) {
        User currentUser = userService.getCurrentUser();
        if (currentUser == null || !currentUser.getRoleId().equals(2L)) {
            throw new RuntimeException("非商家用户");
        }

        Merchant merchant = getMerchantByUserId(currentUser.getId());
        if (merchant == null) {
            throw new RuntimeException("商家信息不存在");
        }

        merchant.setShopName(dto.getShopName());
        merchant.setDescription(dto.getDescription());
        merchant.setAddress(dto.getAddress());
        merchant.setShopLogo(dto.getShopLogo());
        merchant.setBusinessLicense(dto.getBusinessLicense());

        merchantMapper.updateById(merchant);
    }

    @Override
    @Transactional
    public void updateStatus(Long id, Integer status) {
        Merchant merchant = merchantMapper.selectById(id);
        if (merchant == null) {
            throw new RuntimeException("商家不存在");
        }
        
        merchant.setStatus(status);
        merchantMapper.updateById(merchant);
    }

    @Override
    public Page<Merchant> list(Integer pageNum, Integer pageSize) {
        Page<Merchant> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Merchant> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("created_at");
        return merchantMapper.selectPage(page, queryWrapper);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        // 1. 检查商家是否存在
        Merchant merchant = merchantMapper.selectById(id);
        if (merchant == null) {
            throw new RuntimeException("商家不存在");
        }

        // 2. 获取该商家的所有商品ID
        QueryWrapper<Furniture> furnitureQueryWrapper = new QueryWrapper<>();
        furnitureQueryWrapper.eq("merchant_id", id);
        
        // 3. 删除购物车中的商品记录
        cartMapper.deleteByMerchantId(id);
        
        // 4. 删除商品评论的点赞记录
        reviewMapper.deleteLikesByMerchantId(id);
        
        // 5. 删除商品的评论
        reviewMapper.deleteByMerchantId(id);
        
        // 6. 删除订单项
        orderItemMapper.deleteByMerchantId(id);
        
        // 7. 删除订单
        orderMapper.deleteByMerchantId(id);
        
        // 8. 删除商家的所有商品
        furnitureMapper.delete(furnitureQueryWrapper);
        
        // 9. 删除商家信息
        merchantMapper.deleteById(id);
        
        // 10. 删除关联的用户信息
        userMapper.deleteById(merchant.getUserId());
    }
}